/**
 *
 * @author zzhijie
 * @date 2020-11-17
 */

export function getRandomKey() {
  const letterStr = '0123456789abcdefghijklmnopqrstuvwxyz';
  let str = '';
  for (let i = 0; i < 12; i++) {
    str += letterStr[(Math.random() * 35 | 0)];
  }
  return str;
}

//验证手机号码
export const checkMobil = (rule, value, cb) => {
  const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/;

  if (regMobile.test(value)) {
    return cb();
  }
  cb(new Error('请输入合法手机号'));
};

export function getDate(str = '') {
  let arr = str.split(/[- /:]/g);
  if (arr.length) {
    return new Date(+arr[0], arr[1] - 1, +arr[2], +arr[3] || 0, +arr[4] || 0, +arr[5] || 0);
  } else {
    return new Date();
  }
}

/**
 * 日期格式化
 */
export function dateFormat(date, format = 'yyyy-MM-dd hh:mm:ss') {
  if (date != 'Invalid Date') {
    var o = {
      'M+': date.getMonth() + 1, //month
      'd+': date.getDate(), //day
      'h+': date.getHours(), //hour
      'm+': date.getMinutes(), //minute
      's+': date.getSeconds(), //second
      'q+': Math.floor((date.getMonth() + 3) / 3), //quarter
      'S': date.getMilliseconds() //millisecond
    };
    if (/(y+)/.test(format)) format = format.replace(RegExp.$1,
      (date.getFullYear() + '').substr(4 - RegExp.$1.length));
    for (var k in o)
      if (new RegExp('(' + k + ')').test(format))
        format = format.replace(RegExp.$1,
          RegExp.$1.length == 1 ? o[k] :
            ('00' + o[k]).substr(('' + o[k]).length));
    return format;
  }
  return '';
}

/**
 * 获取一段日期范围内的星期
 * @param {*} begin - 开始日期
 * @param {*} end   - 结束日期
 * @param {Array} weeks - [0,1,2,3,4,5,6]
 * @returns
 */

export function getWeek(begin, end, weeks) {
  var dateArr = new Array();
  var stimeArr = begin.split('-');
  var etimeArr = end.split('-');

  var stoday = new Date();
  stoday.setUTCFullYear(stimeArr[0], stimeArr[1] - 1, stimeArr[2]);
  var etoday = new Date();
  etoday.setUTCFullYear(etimeArr[0], etimeArr[1] - 1, etimeArr[2]);

  var unixDb = stoday.getTime(); // 开始时间的毫秒数
  var unixDe = etoday.getTime(); // 结束时间的毫秒数

  for (var k = unixDb; k <= unixDe;) {
    let needJudgeDate = msToDate(parseInt(k)).withoutTime;
    // 不加这个if判断直接push的话就是已知时间段内的所有日期
    for (var i = 0; i < weeks.length; i++) {
      if (new Date(needJudgeDate).getDay() === weeks[i]) {
        dateArr.push(needJudgeDate);
      }
    }
    k = k + 24 * 60 * 60 * 1000;
  }
  return dateArr;
}


/**
 * 毫秒转日期
 * @param {*} msec
 * @returns
 */
export function msToDate(msec) {
  let datetime = new Date(msec);
  let year = datetime.getFullYear();
  let month = datetime.getMonth();
  let date = datetime.getDate();
  let hour = datetime.getHours();
  let minute = datetime.getMinutes();
  let second = datetime.getSeconds();

  let result1 = year +
    '-' +
    ((month + 1) >= 10 ? (month + 1) : '0' + (month + 1)) +
    '-' +
    ((date + 1) < 10 ? '0' + date : date) +
    ' ' +
    ((hour + 1) < 10 ? '0' + hour : hour) +
    ':' +
    ((minute + 1) < 10 ? '0' + minute : minute) +
    ':' +
    ((second + 1) < 10 ? '0' + second : second);

  let result2 = year +
    '-' +
    ((month + 1) >= 10 ? (month + 1) : '0' + (month + 1)) +
    '-' +
    ((date + 1) < 11 ? '0' + date : date);

  let result = {
    hasTime: result1,
    withoutTime: result2
  };

  return result;
}

/**
 * 获取两日期之间的日期列表
 * @param {*} sDate - 开始日期
 * @param {*} eDate - 结束日期
 * @returns {array}
 */

export function getDiffDate(sDate, eDate) {
  let diffdate = new Array();
  let i = 0;
  while (sDate <= eDate) {
    diffdate[i] = sDate;
    let stime_ts = new Date(sDate).getTime();
    // 增加一天时间戳后的日期
    let next_date = stime_ts + (24 * 60 * 60 * 1000);
    // 拼接年月日，这里的月份会返回（0-11），所以要+1
    let next_dates_y = new Date(next_date).getFullYear() + '-';
    let next_dates_m = (new Date(next_date).getMonth() + 1 < 10) ? '0' + (new Date(next_date).getMonth() + 1) + '-' : (new Date(next_date).getMonth() + 1) + '-';
    let next_dates_d = (new Date(next_date).getDate() < 10) ? '0' + new Date(next_date).getDate() : new Date(next_date).getDate();
    sDate = next_dates_y + next_dates_m + next_dates_d;
    i++;
  }
  return diffdate;
}

export function print(dom) {
  if (!dom) return;
  setTimeout(() => {
    let style = document.head.querySelector('.print-style');
    if (!style) {
      style = document.createElement('style');
      style.className = 'print-style';
      style.innerText = '@media print {#app {display: none}}';
      document.head.appendChild(style);
    }
    dom.style.color = '#000';
    document.body.appendChild(dom);
    window.print();
    document.body.removeChild(dom);
  });
}
